/* eslint-disable eqeqeq */

<template>
  <div class="library-pepole-tree-container">
    <el-input style="margin-bottom:10px"
              placeholder="请输入"
              prefix-icon="el-icon-search"
              v-model="filterText">
    </el-input>
    <div :style="{'height':treeHeight,'overflow-y':'auto'}">
      <!-- :default-expanded-keys="selectedNodeList"   treeHeight-->
      <el-tree class="treeShow"
               :data="treeDataChild"
               :props="defaultPropsShowAllCom"
               label="node_name"
               node-key="node_id_desc"
               ref="organizationTree"
               :default-checked-keys="defaultCheckedKeys"
               :highlight-current="true"
               :filter-node-method="filterNode"
               :expand-on-click-node="true"
               :default-expand-all="false"
               @node-contextmenu="rihgtClick"
               @node-expand="getId"
               @node-click="getId"
               @node-collapse="deleteNodeIdDesc"
               :default-expanded-keys="selectedNodeList"
               :auto-expand-parent="false"
               draggable
               :accordion="false"
               :check-strictly="true"
               @check="treeCheckChange"
               :show-checkbox="checkbox">
        <span class="slot-t-node"
              slot-scope="{ node, data }">
          <span v-show="!node.isEdit">
            <span v-show="data.children && data.children.length >= 1">
              <!-- <i class="fa"
                 :class="{'fa-building':data.node_type==='1','fa-institution':data.node_type==='2','fa-user-circle':data.node_type==='3'}" /> -->
              <img :src="data.node_type==='1'? require(`@/assets/guideImg/dw-ic.png`)  :(data.node_type==='2'&&data.dept_type!='2')? require(`@/assets/guideImg/bm-ic.png`) : (data.node_type==='2'&&data.dept_type=='2')?require(`@/assets/img/xm-ic.png`):require(`@/assets/guideImg/gw-ic.png`) "
                   alt="">
              <span :class="[data.node_id_desc >= maxexpandId ? 'slot-t-node--label' : '']"
                    :title="data.system_name||data.node_name">{{data.node_name}}</span>
            </span>
            <!-- 当树形节点不存在子节点时，设置单独的图标 -->
            <span v-show="!data.children || data.children.length == 0">
              <!-- <i class="fa"
                 :class="{'fa-building':data.node_type==='1','fa-institution':data.node_type==='2','fa-user-circle':data.node_type==='3'}"></i> -->
              <img :src="data.node_type==='1'? require(`@/assets/guideImg/dw-ic.png`)  :(data.node_type==='2'&&data.dept_type!='2')? require(`@/assets/guideImg/bm-ic.png`) : (data.node_type==='2'&&data.dept_type=='2')?require(`@/assets/img/xm-ic.png`):require(`@/assets/guideImg/gw-ic.png`) "
                   alt="">
              <span :class="[data.node_id_desc >= maxexpandId ? 'slot-t-node--label' : '']"
                    :title="data.system_name||data.node_name">{{data.node_name }}</span>
            </span>
          </span>
          <!-- 编辑输入框 -->
          <span v-show="node.isEdit">
            <el-input class="slot-t-input"
                      size="mini"
                      autofocus
                      v-model="data.name"
                      :ref="'slotTreeInput'+data.node_id_desc"
                      @blur.stop="NodeBlur(node, data)"
                      @keyup.enter.native="NodeBlur(node, data)"></el-input>
          </span>
        </span>
      </el-tree>
    </div>

    <!--鼠标右键点击出现页面-->

    <div v-show="menuVisible">

      <el-menu id="rightClickMenu"
               class="el-menu-vertical"
               @select="handleRightSelect"
               active-text-color="#fff"
               text-color="#fff">

        <!-- 根据不同的状态，显示不同的右键自定义菜单（岗位与非岗位状态） -->

        <el-menu-item index="1"
                      v-show="DATA.node_type==='1'"
                      class="menuItem">
          <i class="el-icon-plus" />
          <span slot="title">新增单位</span>
        </el-menu-item>
        <el-menu-item index="2"
                      class="menuItem"
                      v-show="DATA.node_type!==3">
          <i class="el-icon-edit" />
          <span slot="title">新增部门</span>
        </el-menu-item>

        <el-menu-item index="3"
                      class="menuItem"
                      v-show="DATA.node_type==='2'">
          <i class="el-icon-edit" />
          <span slot="title">新增岗位</span>
        </el-menu-item>
        <el-menu-item index="6"
                      class="menuItem"
                      v-show="DATA.node_type==='3'">
          <i class="el-icon-edit" />
          <span slot="title">分配人员</span>
        </el-menu-item>
        <!-- 
        <el-menu-item index="7"
                      class="menuItem"
                      v-show="DATA.node_type==='3'">

          <i class="el-icon-edit" />

          <span slot="title">分配权限模板</span>

        </el-menu-item>
        <el-menu-item index="8"
                      class="menuItem"
                      v-show="DATA.node_type==='3'">
          <i class="el-icon-edit" />
          <span slot="title">分配权限</span>
        </el-menu-item> -->
        <el-menu-item index="4"
                      class="menuItem">
          <i class="el-icon-circle-plus-outline" />
          <span slot="title">修改</span>
        </el-menu-item>

        <el-menu-item index="5"
                      class="menuItem">
          <i class="el-icon-menu" />
          <span slot="title">删除</span>
        </el-menu-item>
      </el-menu>
    </div>

    <!-- 新增或修改子单位弹框 -->
    <EditOrgDialog @callback="editCallback"
                   :dialogVisible.sync="editOrgDialogVisible"
                   :dialogForm="editOrgDialogForm"
                   :dialogStatus.sync="editOrgDialogStatus"></EditOrgDialog>

    <!-- 新增或修改部门弹框 -->

    <EditDeptDialog @callback="editCallback"
                    :dialogVisible.sync="editDeptDialogVisible"
                    :dialogForm="editDeptDialogForm"
                    :dialogStatus.sync="editDeptDialogStatus"
                    :treeDataChild.sync="treeDataChild"></EditDeptDialog>

    <!-- 新增或修改岗位弹框 -->

    <EditJobDialog @callback="editCallback"
                   :dialogVisible.sync="editJobDialogVisible"
                   :dialogForm="edittJobDialogForm"
                   :dialogStatus.sync="editJobDialogStatus"></EditJobDialog>

  </div>

</template>

<script>
import { backEvaluateApi } from '@/services/ProjectCenter'
import { ApplicationMarketManageApi } from '@/services/ResourceCentre'
import { organizationApi } from '@/services/CompanySetting'
import EditOrgDialog from './components/EditOrgDialog'
import EditDeptDialog from './components/EditDeptDialog'
import EditJobDialog from './components/EditJobDialog'
// import { compile } from 'vue/types/umd'
// import api from '../../resource/api.js'

export default {
  name: 'OrganizationTree',
  components: {
    EditOrgDialog,
    EditDeptDialog,
    EditJobDialog
  },
  data () {
    return {
      str: '',
      dataArr: [],//遍历的新数据
      defaultCheckedKeys: [],//默认当前选中
      treeDataChild: [],//展示全部的单位
      judge: '',
      filterText: '',
      NODE: {},
      DATA: {},
      maxexpandId: 95, // 新增节点开始id
      non_maxexpandId: 95, // 新增节点开始id(不更改)
      isLoadingTree: true, // 是否加载节点树
      //   setTree:api.treelist,//节点树数据

      defaultProps: {
        children: 'children',
        label: 'name',
        disabled: (data) => {
          return data.node_type !== '3'
        }
      },

      defaultPropsShowAllCom: {
        children: 'children',
        label: 'node_name'
      },
      menuVisible: false,
      objectID: null,
      // 编辑或新增
      addOrEdit: 'add',
      // 选中的节点列表，用于刷新后展开到指定位置
      selectedNodeList: [],
      // 编辑单位弹框是否可见
      editOrgDialogVisible: false,
      // 编辑单位弹框数据对象
      editOrgDialogForm: {
      },

      // 编辑单位弹框处于新增或修改状态
      editOrgDialogStatus: 'create',
      // 编辑部门弹框是否可见
      editDeptDialogVisible: false,
      // 编辑部门弹框数据对象
      editDeptDialogForm: {
      },
      // 编辑单位弹框处于新增或编辑状态
      editDeptDialogStatus: 'create',
      // 编辑岗位弹框是否可见
      editJobDialogVisible: false,
      // 编辑岗位弹框数据对象
      edittJobDialogForm: {
      },
      // 编辑岗位弹框处于新增或编辑状态
      editJobDialogStatus: 'create',
      nodeIdsAr: [],
      companyNamesAr: [],
    }
  },

  props: {
    isRefresh: {
      type: Boolean,
      default: () => {
        return false
      }
    },
    isDelete: {
      type: Boolean,
      default: () => {
        return false
      }
    },
    treeHeight: {
      type: String,
      default: () => {
        return '350px'
      }
    },
    isSupportOpera: {
      type: Boolean,
      default: () => {
        return true
      }
    },
    showAllCompany: {
      type: Number,
      default: 0,//不展示所有的单位
    },
    //节点回显
    nodeIdsArr: {
      type: Array,
      default: () => {
        return []
      }
    },
    compKeysArr: {
      type: Array,
      default: () => {
        return []
      }
    },
    companyNamesArr: {
      type: Array,
      default: () => {
        return []
      }
    },
    curMenu: Object,
    assignedNode: Object,
    assignedTemplateNode: Object,
    assignedPermissionNode: Object,
    // 复选框
    checkbox: {
      type: Boolean,
      default: false,//false
    },
    // 是否启用右键菜单编辑功能

    rightMenu: {
      type: Boolean,
      default: true
    },
    selectProject: {
      type: Boolean,
      default: false
    },
    // 筛选职能部门或项目部门，0表示全部，1表示职能部门，2表示项目部门
    deptSort: {
      type: Number,
      default: 0
    }
  },
  methods: {
    //选中的node_id_desc集合
    getNodeIdsAr (treeList, isSelected) {
      let arr = [];
      if (this.nodeIdsAr.indexOf(treeList.node_id_desc) == -1 && isSelected == true) {//添加
        this.nodeIdsAr.push(treeList.node_id_desc);
        this.companyNamesAr.push(treeList);
      };
      if (isSelected == false) {//删除
        let count = 0;
        if (this.nodeIdsAr.length > 0) {
          this.nodeIdsAr.map((item, ind, arr1) => {
            if (item == treeList.node_id_desc) {
              count = ind;
            }
          });
          this.nodeIdsAr.splice(count, 1);
          this.companyNamesAr.splice(count, 1);
        }
      };
      arr = this.nodeIdsAr;
      return arr;
    },
    // 统一处理子节点为相同的勾选状态
    uniteChildSame (treeList, isSelected) {
      this.$refs.organizationTree.setChecked(treeList.node_id_desc, isSelected);
      this.$emit('update:nodeIdsArr', this.getNodeIdsAr(treeList, isSelected));
      this.$emit('update:companyNamesArr', this.companyNamesAr);
      if (treeList.children) {//存在就执行下面的操作
        for (let i = 0; i < treeList.children.length; i++) {
          if (treeList.children[i].node_type != 3 && treeList.children[i].children) {
            this.uniteChildSame(treeList.children[i], isSelected)
          } else if (treeList.children[i].node_type != 3 && !treeList.children[i].children) {
            this.$refs.organizationTree.setChecked(treeList.children[i].node_id_desc, isSelected);
            this.$emit('update:nodeIdsArr', this.getNodeIdsAr(treeList.children[i], isSelected));
          }
        }
      }
    },
    // 统一处理父节点为选中
    selectedParent (currentObj) {
      let currentNode = this.$refs.organizationTree.getNode(currentObj)
      if (currentNode.parent.key !== undefined) {
        this.$refs.organizationTree.setChecked(currentNode.parent, true)
        this.selectedParent(currentNode.parent)
      };
    },
    treeCheckChange (currentObj, treeStatus) {
      // 用于：父子节点严格互不关联时，父节点勾选变化时通知子节点同步变化，实现单向关联。
      let selected = treeStatus.checkedKeys.indexOf(currentObj.node_id_desc) // -1未选中
      // 选中
      if (selected !== -1) {
        // 子节点只要被选中父节点就被选中
        this.selectedParent(currentObj)
        // 统一处理子节点为相同的勾选状态
        this.uniteChildSame(currentObj, true)
      } else {
        // 未选中 处理子节点全部未选中
        // if (currentObj.children.length !== 0) {
        this.uniteChildSame(currentObj, false)
        // this.$emit('update:nodeIdsArr', this.getNodeIdsAr(currentObj, false));
        // }
      };
    },
    jobAddDisabled (data) {//项目树
      if (data.length > 0) {
        data.map((item) => {
          if (item.node_type == 3) {//岗位不允许选择
            this.$set(item, 'disabled', true);
          };
          if (item.children) {
            this.jobAddDisabled(item.children);
          }
        })
      };
      return data
    },
    //获取obs-项目树
    getObsTree () {
      return backEvaluateApi.getObsTree({
        params: {}
      }).then(async (res) => {
        if (res.code == 0) {
          let data = res.data;
          this.treeDataChild = this.jobAddDisabled(data);//项目树
        }
      }).catch((error) => {
        console.log(error)
      })
    },
    // 新增
    onAdd () {
      this.judge = 1
    },
    onEdit () {
      this.judge = 2
    },
    deleteNodeIdDesc (data, node) {//节点收起时执行（解决点击左边的三角形,事件不触发的问题）
      let curData = JSON.parse(JSON.stringify(data))
      this.menuVisible = false
      this.$emit('update:curMenu', curData)
      this.removeNodeList(data.node_id_desc);//节点收起时执行
    },
    // 节点点击事件获取id
    getId (data, node) {
      let curData = JSON.parse(JSON.stringify(data))
      this.menuVisible = false
      this.$emit('update:curMenu', curData)
      // this.$emit('update:showAll', 0);//是否展示所有的单位
      if ((node.expanded || node.childNodes.length === 0) && data.node_id_desc) {//添加
        this.addNodeList(data.node_id_desc)
      }
      // else {
      //   this.removeNodeList(data.node_id_desc)
      // };
    },
    // 当当前节点是展开操作时,将当前节点的object_id添加到selectedNodeList中，为了刷新数据后能够展开到指定位置
    addNodeList (id) {
      let index = this.selectedNodeList.indexOf(id)
      if (index < 0) {
        this.selectedNodeList.push(id)
      };
    },
    // 当前节点是收起操作时，将当前节点的object_id从selectedNodeList中移除
    removeNodeList (id) {
      let index = this.selectedNodeList.indexOf(id)
      if (index >= 0) {
        this.selectedNodeList.splice(index, 1)
      }
    },
    // 对树节点进行筛选时执行的方法，返回 true 表示这个节点可以显示，返回 false 则表示这个节点会被隐藏
    filterNode (value, data) {
      if (!value) return true
      // return data.menu_name.indexOf(value) !== -1
      return data.node_name.indexOf(value) !== -1;//工作中心-关联组织菜单中-关联按钮触发后的弹框树形模糊查询会用到
    },
    getCurrentPosition (currentPosition) {
      let isGreaterThan5 = false;//当前的位置是否大于500
      if (currentPosition > 550) {
        isGreaterThan5 = true;
      }
      return isGreaterThan5;
    },
    // 右键点击事件
    rihgtClick (event, object, value, element) {
      this.DATA = object
      this.$set(this.DATA, 'p_id', object.node_id_desc)
      this.NODE = value;
      if (this.isSupportOpera == true) {//当isSupportOpera为true时，操作框才展示
        if (this.rightMenu) {
          this.menuVisible = !this.menuVisible
          document.addEventListener('click', e => {
            this.menuVisible = false
          })
          let menu = document.querySelector('#rightClickMenu');
          //是否在上面展示
          let layerY = event.layerY;
          let isGreaterThan5 = this.getCurrentPosition(layerY);
          if (isGreaterThan5 == true) {
            layerY = layerY - 240;
          }
          /* 菜单定位基于鼠标点击位置 */
          menu.style.left = event.clientX + 20 - 200 + 'px'
          // menu.style.top = event.clientY - 90 + 'px'
          menu.style.top = layerY + 140 + 'px'
          menu.style.position = 'absolute' // 为新创建的DIV指定绝对定位
          menu.style.width = 160 + 'px';
        }
      }
    },
    // 右键弹出的菜单点击事件
    handleRightSelect (key) {
      this.$emit('update:isDelete', false)
      if (key === '1') {
        // 新增单位
        this.editOrg('create')
      } else if (key === '2') {
        // 新增部门
        this.editDept('create')
      } else if (key === '3') {
        // 新增岗位
        this.editJob('create')
      } else if (key === '4') {
        // 修改，需要区分单位、部门、岗位
        // node_type为1是单位，2是部门，3是岗位
        if (this.DATA.node_type === '1') {
          this.editOrg('update')
        } else if (this.DATA.node_type === '2') {
          this.editDept('update')
        } else if (this.DATA.node_type === 3) {
          this.editJob('update')
        }
      } else if (key === '5') {
        // 删除功能，需要区分单位、部门、岗位
        this.NodeDel(this.NODE, this.DATA)
      } else if (key === '6') {
        // 分配人员
        this.$emit('update:assignedNode', this.DATA)
      } else if (key === '7') {
        // 分配权限模板
        this.$emit('update:assignedTemplateNode', this.DATA)
      } else if (key == 8) {
        // 分配权限
        this.$emit('update:assignedPermissionNode', this.DATA)
      }
      this.menuVisible = false
    },

    NodeBlur (n, d) {
      // 输入框失焦
      if (n.isEdit) {
        this.$set(n, 'isEdit', false)
      }
      this.$nextTick(() => {
        this.$refs['slotTreeInput' + d.node_id_desc].$refs.input.focus()
      })
    },
    NodeDel (n, d) {
      // // 删除节点
      // if (d.children && d.children.length !== 0) {
      //   this.$message.error('此菜单有子菜单，不可删除！')
      //   return false
      // } else {
      //   // 二次确认
      let ConfirmFun = () => {
        this.$confirm('是否删除此菜单？', '提示', {
          confirmButtonText: '确认',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          let nodeType = this.DATA.node_type === '1' || this.DATA.node_type === '2' || this.DATA.node_type === 3;
          if (nodeType) {
            this.deleteOrgDeptJob(this.DATA.node_type);//删除单位/部门/岗位
          }
        })
          .catch(() => { })
      }
      // 判断是否是新增节点
      ConfirmFun()
      // }
    },
    // 新增或修改单位弹框
    editOrg (type) {
      this.editOrgDialogVisible = true;
      this.editOrgDialogForm = this.DATA;
      this.editOrgDialogStatus = type;
    },

    // 新增或修改部门弹框
    editDept (type) {
      this.editDeptDialogVisible = true
      this.editDeptDialogForm = this.DATA
      this.editDeptDialogStatus = type
    },
    // 新增或修改岗位弹框
    editJob (type) {
      this.editJobDialogVisible = true
      this.edittJobDialogForm = this.DATA
      this.editJobDialogStatus = type
    },
    // 删除岗位
    deleteOrgDeptJob (nodeType) {
      backEvaluateApi.delObs({
        data: {
          node_id: this.DATA.node_id,
          node_type: this.DATA.node_type,
        }
      }).then(res => {
        if (res.code === 0) {
          let nodeTypeRemark = nodeType == 1 ? '删除单位成功' : nodeType == 2 ? '删除部门成功' : '删除岗位成功'
          this.$message.success(nodeTypeRemark);
          this.getObsTree();
          this.$emit('update:isDelete', true)
        }
      })
    },

    // 处理传入的数据，因为后端都是children，需要手动赋值一个children字段
    handelData (arr, parentName, parentNo) {
      if (Object.prototype.toString.call(arr) === '[object Array]') {
        for (let i = 0; i < arr.length; i++) {
          let item = arr[i]
          item.uniqId = item.node_id_desc + item.no
          item.p_name = parentName
          item.parent_no = parentNo
          // 筛选职能部门或项目部门
          if (item.node_type === '2' && this.deptSort !== 0) {
            if (Number(item.dept_type) !== this.deptSort) {
              // arr.splice(i, 1)
              // i--
              item.disabled = true
            }
          }
          if (item.children) {
            item.children = item.children
            this.handelData(item.children, item.name, item.no)
          } else if (item.childrens) {
            item.children = item.childrens
            this.handelData(item.childrens, item.name, item.no)
          }
          if (this.selectProject === true) {
            if (item.node_type === '2') {
              // item.children = []
            }
          }
          if (item.sid) {
            item.menu_id = item.sid
          }
          if (item.menu_id === '') {
            item.menu_id = '0'
          }
        }
        return arr
      }
    },
    // 编辑成功回调
    editCallback () {
      this.getObsTree();//刷新
    },
  },
  watch: {
    isRefresh (n, o) {//是否刷新
      if (n == true) {
        this.getObsTree();//刷新
      }
    },
    companyNamesArr (n, o) {
      this.companyNamesAr = n;
    },
    nodeIdsArr (n, o) {
      this.$nextTick(() => {
        this.$refs.organizationTree.setCheckedKeys(n);//清空
        this.nodeIdsAr = n;
        this.defaultCheckedKeys = n;//回显
      });
    },
    filterText (val) {
      this.$refs.organizationTree.filter(val)
    },
  },
  activated () {
    if (this.treeDataChild.length == 0 || this.isRefresh == true) {
      // this.getObsTree();//单位
    };
  },
  created () {
    this.$nextTick(async () => {
      this.companyNamesAr = this.companyNamesArr;
      this.$refs.organizationTree.setCheckedKeys(this.nodeIdsArr);//清空
      this.defaultCheckedKeys = this.nodeIdsArr;//回显
      if (this.treeDataChild.length == 0) {
        await this.getObsTree();//单位
      };
      this.selectedNodeList = [];
    });
  }
}
</script>

<style lang="scss" scoped>
/deep/ .el-tree {
  //height: 100% !important;
}

/* 去掉默认的树形图标 */

/* .treeShow /deep/ .el-tree-node__content>.el-tree-node__expand-icon {

  display: none;

} */

#save-style {
  background: rgba(26, 188, 156, 1);

  color: white;
}

#back-style {
  background: rgba(26, 188, 156, 1);
}

#show-ellipsis {
  //display: block;

  width: 100%;

  overflow: hidden;

  white-space: nowrap;

  text-overflow: ellipsis;
}

.popover-new {
  /* position: absolute!important;

    right: 0;

    bottom: 0; */
}

/*顶部按钮*/

.slot-tree .slot-t-top {
  margin-bottom: 15px;
}

.slot-tree .slot-t-node span {
  display: inline-block;
}

/*节点*/

.slot-tree .slot-t-node--label {
  font-weight: 600;
}

/*输入框*/

.slot-tree .slot-t-input .el-input__inner {
  height: 26px;

  line-height: 26px;
}

/*按钮列表*/

.slot-tree .slot-t-node .slot-t-icons {
  display: none;

  margin-left: 10px;
}

.slot-tree .slot-t-icons .el-button + .el-button {
  margin-left: 6px;
}

.slot-tree .el-tree-node__content:hover .slot-t-icons {
  display: inline-block;
}

/*************************标签鼠标右击页面样式******************************/

.el-menu-vertical {
  /* border: 3px solid rgb(84, 92, 100); */

  border: 2px solid #f5f7fa;

  border-radius: 10px;

  z-index: 100;
}

.el-menu-vertical i {
  color: #777777;
}

.menuItem {
  height: 40px;

  line-height: 40px;

  /* background-color: #545c64; */

  background-color: #f5f7fa;

  font-size: 14px;
}

/deep/ .menuItem i {
  color: #606266 !important;
}

/deep/ .menuItem span {
  color: #606266 !important;
}

.menuItem:hover {
  background-color: #409eff;
}

/deep/ .menuItem:hover i {
  color: #fff !important;
}

/deep/ .menuItem:hover span {
  color: #fff !important;
}

.add_tips /deep/ .el-form-item__label {
  /* padding-left: 28px; */
}

.library-pepole-tree-container {
  min-height: 400px;
}

.organization-tree-container {
  margin-top: 20px !important;

  width: 100% !important;

  min-height: 260px;

  background-color: #fff;
}
</style>